/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.guide.web;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.number.RandomUtil;
import com.jeeplus.common.web.Result;
import com.jeeplus.config.properties.JeePlusProperites;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.guide.entity.*;
import com.jeeplus.modules.guide.model.query.CancelAppointment;
import com.jeeplus.modules.guide.model.query.ModAppointment;
import com.jeeplus.modules.guide.model.vo.AppointmentRecordOut;
import com.jeeplus.modules.guide.model.vo.ModAppointmentOut;
import com.jeeplus.modules.guide.model.vo.ServiceTime;
import com.jeeplus.modules.guide.service.AppointmentService;
import com.jeeplus.modules.guide.service.MobileMatterService;
import com.jeeplus.modules.guide.service.MobileQueueService;
import com.jeeplus.modules.guide.service.*;
import com.jeeplus.modules.guide.task.Send;
import com.jeeplus.modules.guide.utils.*;
import com.jeeplus.modules.sys.entity.MobileGxUser;
import com.jeeplus.modules.sys.entity.MobileLegal;
import com.jeeplus.modules.sys.entity.MobileUserQR;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.security.util.JWTUtil;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.sys.utils.EncryptUtils;
import com.jeeplus.modules.sys.utils.FileKit;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.work.queue.service.ElectronicMaterialService;
import lombok.RequiredArgsConstructor;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.io.*;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 排队叫号对接Controller
 * @author azj
 * @version 2021-5-15
 */
@RestController
@RequestMapping("/mobileQueue")
@RequiredArgsConstructor
public class MobileQueueController extends BaseController {
	//对接AppKeyValue
	@Value("${AppKeyValue}")
	private String AppKeyValue;

	//排队叫号QueueUrl
	@Value("${QueueUrl}")
	private String QueueUrl;

	//业务分组-预约
	@Value("${QueueYYType}")
	private String QueueYYType;

	//私钥
	@Value("${GX_PUBLIC_KEY}")
	private String GX_PUBLIC_KEY;

	//二维码失效时间
	@Value("${loseTime}")
	private int loseTime;

	//公安KEY
	@Value("${gongAnKey}")
	private String gongAnKey;

	//注册基础信息
	@Value("${pwd}")
	private String pwd;
	//二维码地址
	@Value("${qrUrl}")
	private String qrUrl;
	//guixi地址
	@Value("${guixi}")
	private String guixi;
	//xiyuan地址
	@Value("${xiyuan}")
	private String xiyuan;
	//zhonghe地址
	@Value("${zhonghe}")
	private String zhonghe;
	//shiyang地址
	@Value("${shiyang}")
	private String shiyang;
	//hezuo地址
	@Value("${hezuo}")
	private String hezuo;
	//室内地址获取接口
	@Value("${snUrl}")
	private String snUrl;

	private final MobileXJHQueueService mobileXJHQueueService;
	private final MobileQueueService mobileQueueService;
	private final MobileXQQueueService mobileXQQueueService;
	private final AppointmentService appointmentService;
	private final MobileIndexService mobileIndexService;
	private final UserService userService;
	private final MobileMatterService mobileMatterService;
	private final MobileLoginService mobileLoginService;
	private final MobileSilentService mobileSilentService;
	private final MobilePublicSecurityTwoService mobilePublicSecurityTwoService;
	private final Send send;
	private static final Logger log = LoggerFactory.getLogger(MobileQueueController.class);
    private final ElectronicMaterialService electronicMaterialService;
	private final RongYiBanService rongYiBanService;
	//街道网上办链接
	private static final String guixiurl = "https://gxzh.cdht.gov.cn/";
	private static final String xiyuanurl = "https://xyfw.cdht.gov.cn/";
	private static final String zhongheurl = "http://szzh.cdht.gov.cn/";
	private static final String shiyangurl = "http://gxsy.cdht.gov.cn/";
	private static final String hezuourl = "https://gxhz.cdht.gov.cn/";
	private static final String toStreetValue = "api/v4/yaw/flows/flowid/journeys/journeysid";
	private static final String toTitleValue = "/api/v4/yaw/flows/";
	/**
	 * listArea 获取排队叫号大厅集合
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "listArea")
	public AjaxJson listArea(@RequestHeader("AppKey") String AppKey) {
		if (AppKeyValue.equals(AppKey)) {
			return AjaxJson.success("get data success!").put("data", mobileQueueService.listArea());
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * listAreaAll 获取排队叫号大厅集合
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "listAreaAll")
	public AjaxJson listArea() {
		return AjaxJson.success("get data success!").put("data", mobileQueueService.listArea());
	}

	/**
	 * listAreaType 获取排队叫号大厅业务列表
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "listAreaType")
	public AjaxJson listAreaType(String orgrizeId,String abbreviationName) {
		List<Object> listOBJ = new ArrayList<>();
		if("510109000000".equals(orgrizeId)){
			List<MobileAreaType> list = mobileQueueService.listNQ();
			for(MobileAreaType ma:list){
				List<Map<String,Object>> mapList = new ArrayList<>();
				Map<String,Object> map = new HashedMap();
				map.put("name",ma.getAbbreviationName());
				map.put("abbreviationName",ma.getAbbreviationName());
				map.put("orgrizeId",ma.getOrgrizeId());
				map.put("value",mobileQueueService.findAreaType(ma.getOrgrizeId()));
				mapList.add(map);
				listOBJ.add(mapList);
			}
		}else {
			List<Map<String,Object>> mapList = new ArrayList<>();
			Map<String,Object> map = new HashedMap();
			map.put("name","全部业务");
			map.put("abbreviationName",abbreviationName);
			map.put("orgrizeId",orgrizeId);
			map.put("value",mobileQueueService.findAreaType(orgrizeId));
			mapList.add(map);
			listOBJ.add(mapList);
		}
		return AjaxJson.success("get data success!").put("data", listOBJ);
	}
	/**
	 * listNQ 获取排队叫号南区大厅集合
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "listNQ")
	public AjaxJson listNQ(@RequestHeader("AppKey") String AppKey) {
		if (AppKeyValue.equals(AppKey)) {
			return AjaxJson.success("get data success!").put("data", mobileQueueService.listNQ());
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * listArea 获取排队叫号大厅集合
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "findAreaType")
	public AjaxJson findAreaType(@RequestHeader("AppKey") String AppKey, String orgrizeId) {
		if (AppKeyValue.equals(AppKey)) {
			String[] str = orgrizeId.split(",");
			List<MobileQueueType> list = new ArrayList<>();
			String pdList = "";
			for(String s:str){
				for(MobileQueueType mq : mobileQueueService.findAreaType(s)){
					if(!pdList.contains(mq.getTypeName())){
						list.add(mq);
						pdList += mq.getTypeName()+"-";
					}
				}
			}
			return AjaxJson.success("get data success!").put("data", list);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}


	/**
	 * intoQueue 添加排队号
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "intoQueue")
	public AjaxJson intoQueue(@RequestHeader("AppKey") String AppKey, String orgrizeId, String name, String idcard, String typeNumber) {
		if (AppKeyValue.equals(AppKey)) {
			String result = HttpQueueUtils.intoQueue(QueueUrl, idcard, name, typeNumber, orgrizeId);
			if (StringUtils.isNotBlank(result)) {
				try {
					JSONObject json = JSONObject.fromObject(result);
					result = json.getString("second");
					json = JSONObject.fromObject(result).getJSONObject("data");
					if (json.size() >= 1) {
						return AjaxJson.success("操作成功！").put("data", json);
					} else {
						return AjaxJson.error("取号失败，暂无此业务！");
					}
				} catch (Exception e) {
					return AjaxJson.error("get json is error! reason:" + e.getMessage()).put("code", 400);
				}
			} else {
				return AjaxJson.error("into queue error!").put("code", 400);
			}
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * listArea 获取排队叫号大厅集合
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "findAreaYYType")
	public AjaxJson findAreaYYType(@RequestHeader("AppKey") String AppKey, String orgrizeId) {
		if (AppKeyValue.equals(AppKey)) {
			List<MobileQueueType> list = mobileQueueService.findAreaTypeYY(orgrizeId);
			for (MobileQueueType mt : list) {
				mt.setTypeName(mt.getTypeName().replace("(预约)", "").replace("（预约）", ""));
			}
			return AjaxJson.success("get data success!").put("data", list);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * typeServiceTime 服务时间查询
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/typeServiceTime")
	public AjaxJson typeServiceTime(@RequestHeader("AppKey") String AppKey, String orgrizeId, String id) {
		if (AppKeyValue.equals(AppKey)) {
			return AjaxJson.success("get data success!").put("data", appointmentService.getServiceTime(orgrizeId, id));
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * cancel 取消预约
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/cancel")
	public AjaxJson cancel(@RequestHeader("AppKey") String AppKey,String id) {
		if (AppKeyValue.equals(AppKey)) {
			CancelAppointment obj = new CancelAppointment();
			obj.setId(id);
			return AjaxJson.success("操作成功").put("isDelete",appointmentService.cancel(obj));
		}else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * intoYYQueue 添加预约排队号
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping(value = "intoYYQueue")
	public AjaxJson intoYYQueue(@RequestHeader("AppKey") String AppKey, String idcard, String tell, String name, String orgrizeId, String id, String time, int timePeriod, String abbreviationName) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isBlank(idcard) || StringUtils.isBlank(tell) || StringUtils.isBlank(name) || StringUtils.isBlank(abbreviationName)) {
				return AjaxJson.error("参数不合法！").put("code", 400);
			}
			ModAppointment mt = new ModAppointment();
			mt.setBusinessId(id);
			mt.setSysNo(orgrizeId);
			mt.setTime(time);
			mt.setTimePeriod(timePeriod);
			mt.setSysName(abbreviationName);
			mt.setMatterId("");
			Result<ModAppointmentOut> result = appointmentService.saveAppointment(mt, true, idcard, tell, name);
			if (result.getResp_code() == HttpStatus.OK.value()) {
				return AjaxJson.success("预约成功");
			} else {
				return AjaxJson.error(result.getResp_msg()).put("code", result.getResp_code());
			}
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * getYYQueueValue 预约信息记录
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/getYYQueueValue")
	public AjaxJson getYYQueueValue(@RequestHeader("AppKey") String AppKey, String idcard) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isBlank(idcard)) {
				return AjaxJson.error("参数错误!").put("code", 400);
			}
			return AjaxJson.success("get data success!").put("data", mobileQueueService.findByCardId(idcard));
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * pjListByRCT 预约信息记录
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/pjListByRCT")
	public AjaxJson pjListByRCT(@RequestHeader("AppKey") String AppKey,String type,String cardid,String typeName,String serverTime,String pjMark,String pjLevel, HttpServletRequest request) {

		String  publicIp = UserUtils.getClientIpAddress(request);
		if(userService.checkUserIp(publicIp) <= 0){
			return AjaxJson.error("非法ip:"+publicIp);
		}
		if (AppKeyValue.equals(AppKey)) {
			if("all".equals(type)){
				return AjaxJson.success().put("data",mobileSilentService.pjListByRCTAll());
			}else if("day".equals(type)){
				return AjaxJson.success().put("data",mobileSilentService.pjListByRCTDay());
			}else{
				mobileSilentService.pjListByRCTInto(cardid,typeName,serverTime,pjMark,pjLevel);
				return AjaxJson.success();
			}
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * getQueueValue 获取排队查询
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/getQueueValue")
	public AjaxJson getQueueValue(@RequestHeader("AppKey") String AppKey, String orgrizeId, String number) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isBlank(orgrizeId) || StringUtils.isBlank(number)) {
				return AjaxJson.error("参数错误!").put("code", 400);
			}
			return AjaxJson.success("get data success!").put("data", mobileQueueService.getQueueValue(number, orgrizeId,number.substring(0,number.length()-3)));
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * getQueueValue 获取排队查询
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/getQueueValuecs")
	public AjaxJson getQueueValuecs(String orgrizeId, String number) {
		return AjaxJson.error("AppKey is error!").put("code", mobileSilentService.getQueueValue(number,orgrizeId));
	}

	/**
	 * getOtherQueueValue 西区临时获取群众排队信息 对接卓繁综窗
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/getOtherQueueValue")
	public AjaxJson getOtherQueueValue(@RequestHeader("AppKey") String AppKey, String number) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isBlank(number)) {
				return AjaxJson.error("参数错误!").put("code", 400);
			}
			return AjaxJson.success("get data success!").put("data", mobileXQQueueService.getOtherQueueValue(number));
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * getQueueValue 获取排队用户信息 对接卓繁综窗
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/findUserByNumber")
	public AjaxJson findUserByNumber(@RequestHeader("AppKey") String AppKey, String orgrizeId, String number,String uuid) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isBlank(orgrizeId) && StringUtils.isBlank(number) && StringUtils.isBlank(uuid)) {
				return AjaxJson.error("参数错误!").put("code", 400);
			}
			try {
				MobileQueueUser mq = null;
				if(StringUtils.isNotBlank(uuid)){
					uuid = uuid.substring(uuid.lastIndexOf("/")+1,uuid.length());
					Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
					Matcher m = p.matcher(uuid);
					if(m.find()) {
						return AjaxJson.error("get data is error").put("code", 400);
					}
					MobileGxUser mu = userService.getGxUserCode(uuid);
					if(null == mu){
						return AjaxJson.error("get data is error").put("code", 400);
					}else{
						mq = new MobileQueueUser();
						int sex = Integer.parseInt(mu.getIdcard().substring(16,17));
						if (sex % 2 == 0) {
							mq.setSex("女");
						} else {
							mq.setSex("男");
						}
						mq.setName(mu.getName());
						mq.setAddress(mu.getAddress());
						mq.setMobile(mu.getTell());
						mq.setIdcard(mu.getIdcard());
						return AjaxJson.success("get data success!").put("data", EncryptUtils.aesEncrypt(JSONObject.fromObject(mq).toString(), GX_PUBLIC_KEY));
					}
				}else{
					mq = mobileQueueService.findUserByNumber(number, orgrizeId);
					return AjaxJson.success("get data success!").put("data", EncryptUtils.aesEncrypt(JSONObject.fromObject(mq).toString(), GX_PUBLIC_KEY));
				}
			} catch (Exception e) {
				return AjaxJson.error("get data is error").put("code", 400);
			}
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * 通过一业一证编码获取用户信息
	 * code 一业一证编码
	 * getUserValueByCode
	 *
	 * @return 受影响的行数
	 */
	@RequestMapping(value = "/getUserValueByCode", method = RequestMethod.GET)
	public AjaxJson getUserValueByCode(@RequestHeader("AppKey") String AppKey, String code) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isBlank(code)) {
				return AjaxJson.error("参数错误!").put("code", 400);
			}
			MobileUserQR mobileUserQR = mobileIndexService.getUserValueByCode(code);
			try {
				return AjaxJson.success("get data success!").put("data", EncryptUtils.aesEncrypt(net.sf.json.JSONObject.fromObject(mobileUserQR).toString(), GX_PUBLIC_KEY));
			} catch (Exception e) {
				return AjaxJson.error("get data is error").put("code", 400);
			}
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * 获取用户信息二维码链接
	 * loseTime二维码链接失效时间
	 */
	@RequestMapping(value = "/getUserCode/{uuid}", method = RequestMethod.GET)
	public AjaxJson getUserCode(@PathVariable String uuid) {
		int doTime = loseTime;
		if(uuid.contains("gxls")){
			doTime = 600;
		}
		MobileUserQR mobileUserQR = userService.getUserCode(uuid, doTime);
		try {
			if (null != mobileUserQR && org.apache.commons.lang.StringUtils.isNotBlank(mobileUserQR.getIdcard())) {
				if(uuid.contains("gxls")){
					mobileLoginService.updateUserValue(uuid);
				}
				return AjaxJson.success("加载成功！").put("data", EncryptUtils.aesEncrypt(JSONObject.fromObject(mobileUserQR).toString(), GX_PUBLIC_KEY));
			} else {
				return AjaxJson.error("二维码已失效！").put("code", 400);
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			log.error("二维码获取失败！uuid:" + uuid);
			return AjaxJson.error("二维码获取失败！").put("code", 400);
		}
	}



	/**
	 * 获取用户信息解密密钥
	 * loseTime二维码链接失效时间
	 */
	@RequestMapping(value = "/getKeys", method = RequestMethod.GET)
	public AjaxJson getKeys(String uuid) {
		if(StringUtils.isNotBlank(uuid)){
			String key = userService.findKey(uuid,loseTime);
			if(StringUtils.isNotBlank(key)){
				return AjaxJson.success().put("key",key);
			}
		}
		return AjaxJson.error("二维码已失效");
	}

	/**
	 * checkUserYY 获取用户预约业务
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/checkUserYY")
	public AjaxJson checkUserYY(@RequestHeader("AppKey") String AppKey, String orgrizeId, String idcard) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(orgrizeId) && StringUtils.isNotBlank(idcard)) {
				MobileUserYY mu = mobileQueueService.checkUserYY(idcard, orgrizeId);
				if (null != mu && StringUtils.isNotBlank(mu.getId())) {
					return AjaxJson.success("操作成功！").put("data", mu);
				}
			}
			return AjaxJson.error("当前时间段暂无预约业务!").put("code", 400);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * updateUserYY 更新用户预约状态
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/updateUserYY")
	public AjaxJson updateUserYY(@RequestHeader("AppKey") String AppKey, String id, String number) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(number)) {
				int result = mobileQueueService.updateUserYY(id, number);
				if (result >= 0) {
					return AjaxJson.success("操作成功！");
				}
			}
			return AjaxJson.error("操作失败!").put("code", 400);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * updateUserQueueMatter 通过排队编号录入办理事项信息
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/updateUserQueueMatter")
	public AjaxJson updateUserQueueMatter(@RequestHeader("AppKey") String AppKey, String orgrizeId, String number, String matterId, String matterName) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(orgrizeId) && StringUtils.isNotBlank(number)) {
				int result = mobileQueueService.updateUserQueueMatter(number,orgrizeId,matterId,matterName);
				if (result >= 0) {
					return AjaxJson.success("操作成功！");
				}
			}
			return AjaxJson.error("操作失败!").put("code", 400);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}


	/**
	 * getSwQueue 获取税务排队信息
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/getSwQueue")
	public AjaxJson getSwQueue(@RequestHeader("AppKey") String AppKey, String doTime) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(doTime)) {
				return AjaxJson.success("操作成功！").put("data", mobileQueueService.getSWQueue(doTime));
			}
			return AjaxJson.error("操作失败!").put("code", 400);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * getWSValueAreaAndWino 获取事项办理点位室内导航
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/getWSValueAreaAndWino")
	public AjaxJson getWSValueAreaAndWino(String oid) {
		String result = mobileMatterService.getWSAreaIdAndTypeId(oid);
		if(StringUtils.isNotBlank(result)){
			HashMap<String,Object> maps = mobileSilentService.findWSValueByAreaId(result);
			if(null != maps){
				String wino = mobileSilentService.findWSWino(String.valueOf(maps.get("areaId")),String.valueOf(maps.get("typeNumber")));
				if(StringUtils.isNotBlank(wino) && wino.length() == 1){
					wino = "0"+wino;
				}
				result = HttpRequestUtil.shinei(snUrl,String.valueOf(maps.get("sign")),maps.get("signExpr")+wino);
				if(null != result){
					return AjaxJson.success().put("data",JSONObject.fromObject(result));
				}
			}
		}
		return AjaxJson.error("暂无该事项办理数据！");
	}

	/**
	 * getWSValueAreaAndWino 获取事项办理点位室内导航
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/getSNUrl")
	public AjaxJson getSNUrl() {
		return AjaxJson.success().put("data",HttpRequestUtil.getSNUrl(snUrl));
	}

	/**
	 * 添加第三方街道网上办办件状态数据
	 * intoStreetValue
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/intoStreetValue")
	public AjaxJson intoStreetValue(@RequestHeader("AppKey") String AppKey, String id, String areaName, String status, int code, int areaType, String title, String startTime,String wxId, String tell) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(wxId) && StringUtils.isNotBlank(tell)) {
				int result = mobileMatterService.intoStreetValue(id,areaName,status,code,areaType,title,startTime,wxId,tell);
				if(result >= 1){
					return AjaxJson.success("操作成功！");
				}else{
					return AjaxJson.error("请勿重复添加!").put("code", 400);
				}
			}
			return AjaxJson.error("操作失败!").put("code", 400);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * 修改第三方街道网上办办件状态数据
	 * updateStreetValue
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/updateStreetValue")
	public AjaxJson updateStreetValue(@RequestHeader("AppKey") String AppKey,String status, int code, String updateTime, String id, int areaType) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(id) && StringUtils.isNotBlank(status)) {
				int result = mobileMatterService.updateStreetValue(status,code,updateTime,id,areaType);
				if(result >= 1){
					return AjaxJson.success("操作成功！");
				}
			}
			return AjaxJson.error("操作失败!").put("code", 400);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}


	/**
	 * 获取PC临时登录权限
	 * getPCToken
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/getPCToken")
	public AjaxJson getPCToken(@RequestHeader("AppKey") String AppKey,String openid) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(openid)) {
				String uuid = UUID.randomUUID().toString();
				User users = UserUtils.getByLoginName(openid);
				if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
					if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
						String token = JWTUtil.createAccessToken(openid, users.getPassword());
						mobileLoginService.intoUserToken(uuid,token,openid);
					}
				}
				return AjaxJson.success("操作成功！").put("uuid",uuid);
			}
			return AjaxJson.error("操作失败!").put("code", 400);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * 获取中枢平台临时登录权限
	 * getTokenByZS
	 * @author azj
	 * @version 2020-04-24
	 */
	@CrossOrigin(origins = "*")
	@PostMapping("/getTokenByZS")
	public AjaxJson getTokenByZS(@RequestHeader("AppKey") String AppKey) {
		String openid = "zspt";
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(openid)) {
				String uuid = UUID.randomUUID().toString();
				User users = UserUtils.getByLoginName(openid);
				if (users != null && UserService.validatePassword(pwd, users.getPassword())) {
					if (!(JeePlusProperites.NO.equals(users.getLoginFlag()))) {
						String token = JWTUtil.createAccessToken(openid, users.getPassword());
						mobileLoginService.intoUserToken(uuid,token,openid);
					}
				}
				return AjaxJson.success("操作成功！").put("url","https://zwfw.cdht.org.cn/cdht/#/?GWH=true&uuid="+uuid);
			}
			return AjaxJson.error("操作失败!").put("code", 400);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}

	/**
	 * 清除登录缓存
	 * cleanCacheUser
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/cleanCacheUser")
	public AjaxJson cleanCacheUser(@RequestHeader("AppKey") String AppKey,String openid) {
		if (AppKeyValue.equals(AppKey)) {
			if (StringUtils.isNotBlank(openid)) {
				User users = UserUtils.getByLoginName(openid);
				if(users != null){
					UserUtils.clearCache(users);
				}
			}else{
				UserUtils.clearCache();
			}
			return AjaxJson.error("操作成功!").put("code", 200);
		} else {
			return AjaxJson.error("AppKey is error!").put("code", 400);
		}
	}
	/**
	 * 获取街道办件情况
	 * toStreetValue
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/toStreetValue")
	public AjaxJson intoStreetValue(HttpServletRequest request) {
		String str, body = "";
		try{
			BufferedReader reader = request.getReader();
			while((str = reader.readLine()) != null){
				body += str;
			}
			reader.close();
			if(StringUtils.isNotBlank(body)){
				body = URLDecoder.decode(body, "UTF-8");
			}else{
				return AjaxJson.error("接收内容为空！");
			}
		}catch (Exception e){
			e.printStackTrace();
		}
			JSONObject jsonObject = JSONObject.fromObject(body.trim());
			String userid = jsonObject.getJSONObject("response").getJSONObject("user").getString("id");
			String domain = jsonObject.getJSONObject("response").getJSONObject("mapped_values").getJSONObject("domain").getJSONArray("value").getString(0);
			String flowid = jsonObject.getJSONObject("response").getJSONObject("mapped_values").getJSONObject("flow_id").getJSONArray("value").getString(0);
			String journeyid = jsonObject.getJSONObject("response").getJSONObject("mapped_values").getJSONObject("journey_id").getJSONArray("value").getString(0);
			String url = toStreetValue.replace("flowid",flowid).replace("journeysid",journeyid);
			String authorization = "";
			String name = "";
			if(guixiurl.equals(domain)){
				authorization = guixi;
				name = "桂溪街道网上办";
			}else if(xiyuanurl.equals(domain)){
				authorization = xiyuan;
				name = "西园街道网上办";
			}else if(zhongheurl.equals(domain)){
				authorization = zhonghe;
				name = "中和街道网上办";
			}else if(shiyangurl.equals(domain)){
				name = "石羊街道网上办";
				authorization = shiyang;
			}else if(hezuourl.equals(domain)){
				authorization = hezuo;
				name = "合作街道网上办";
			}
			String result = HttpRequestUtil.getStreetValue(domain+url,authorization);
			String titlrResult = HttpRequestUtil.getStreetValue(domain+toTitleValue+flowid,authorization);
			if(StringUtils.isNotBlank(result) && StringUtils.isNotBlank(titlrResult)){
				MobileStreet ms = new MobileStreet();
				ms.setUserid(userid);
				ms.setName(name);
				ms.setSnid(authorization+flowid);
				jsonObject = JSONObject.fromObject(result);
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				SimpleDateFormat datestr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
				try {
					ms.setStartTime(formatter.format(datestr.parse(jsonObject.getString("created_at"))));
					if(jsonObject.has("updated_at") && StringUtils.isNotBlank(jsonObject.getString("updated_at")))
					ms.setEndTime(formatter.format(datestr.parse(jsonObject.getString("updated_at"))));
				} catch (ParseException e) {
					e.printStackTrace();
				}
				String code = jsonObject.getString("status");
				ms.setCode(code);
				if("stashed".equals(code)){
					ms.setStatus("缓存");
				}else if("processing".equals(code)){
					ms.setStatus("执行");
				}else if("finished".equals(code)){
					ms.setStatus("完成");
				}else if("suspended".equals(code)){
					ms.setStatus("异常");
				}else if("cancelled".equals(code)){
					ms.setStatus("撤销");
				}else if("receding".equals(code)){
					ms.setStatus("回退");
				}else if("aborted".equals(code)){
					ms.setStatus("终止");
				}
				jsonObject = JSONObject.fromObject(titlrResult);
				ms.setTitle(jsonObject.getString("title"));
				mobileMatterService.intoStreetValueOther(ms);
				return AjaxJson.success("操作成功！");
			}
		return AjaxJson.error("接收失败！");
	}

	/**
	 * 获取预约点位
	 * getListAreaValue
	 * @return 受影响的行数
	 */
	//@ApiOperation("获取预约点位")
	@GetMapping(value ="listAreaValue")
	public AjaxJson listAreaValue (){
		return AjaxJson.success().put("data",mobileQueueService.listAreaValue());
	}

	/**
	 * 获取预约点位预约业务
	 * listTypeValueById
	 * @return 受影响的行数
	 */
	//@ApiOperation("获取预约点位预约业务")
	@GetMapping(value ="listTypeValueById")
	public AjaxJson listTypeValueById (String areaId){
		if("510109000000".equals(areaId)){
			return AjaxJson.success().put("data",mobileQueueService.listTypeValueAll(areaId));
		}else return AjaxJson.success().put("data",mobileQueueService.listTypeValueById(areaId));
	}

	/**
	 * 获取线下点位列表
	 * listAreaByWS
	 * @return 受影响的行数
	 */
	@GetMapping(value ="listAreaByWS")
	public AjaxJson listAreaByWS(){
		return AjaxJson.success().put("data",mobileQueueService.listAreaByWS());
	}

	/**
	 * 获取线下点位业务列表
	 * getListAreaWS
	 * @return 受影响的行数
	 */
	@GetMapping(value ="getListAreaWS")
	public AjaxJson getListAreaWS(String areaId){
		return AjaxJson.success().put("data",mobileQueueService.getListAreaWS(areaId));
	}

	/**
	 * 判断是否满足距离
	 * isAreaWS
	 * @return 受影响的行数
	 */
	@GetMapping(value ="isAreaWS")
	public AjaxJson isAreaWS(String areaId,String la,String lo){
		HashMap<String,String> map = mobileQueueService.isAreaWS(areaId);
		if(null != map){
			return AjaxJson.success().put("data",Math.round(DistanceUtils.getDistance(new Double[]{Double.valueOf(la), Double.valueOf(lo)}, new Double[]{Double.valueOf(map.get("longitude")), Double.valueOf(map.get("latitude"))}) * 100.0D) / 100.0D);
		}else{
			return AjaxJson.error("获取点位经纬度失败！").put("code",400);
		}

	}

	/**
	 * 判断是否关注公众号
	 * checkUserWx
	 * @return 受影响的行数
	 */
	@GetMapping(value ="checkUserWx")
	public AjaxJson checkUserWx(String openid){
		if(send.checkUserWx(openid) != null){
			return AjaxJson.success("已关注");
		}else{
			return AjaxJson.error("您尚未关注高新服务公众号，请先关注！");
		}
	}

	/**
	 * findUserByNumberOther 获取排队用户信息 对接省上
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/findUserByNumberOther")
	@CrossOrigin
	public Object findUserByNumberOther(HttpServletRequest req) {
		String ipAddr = req.getRemoteAddr();
		String str, body = "";
		Map<String,Object> result = new HashedMap();
		Map<String,Object> custom = new HashedMap();
		Map<String,Object> status = new HashedMap();
		try{
			BufferedReader reader = req.getReader();
			while((str = reader.readLine()) != null){
				body += str;
			}
			reader.close();
			if("" != body){
				body = URLDecoder.decode(body, "UTF-8");
				JSONObject jsonObject = JSONObject.fromObject(body.trim());
				String orgrizeId = jsonObject.getJSONObject("params").getString("orgrizeId");
				String number = jsonObject.getJSONObject("params").getString("number");
				if(StringUtils.isNotBlank(orgrizeId) && StringUtils.isNotBlank(number)){
					number = number.toUpperCase();
					MobileQueueValue mq = mobileQueueService.getQueueValue(number, orgrizeId,number.substring(0,number.length()-3));
					if(null == mq){
						mq = new MobileQueueValue();
					}
					if(null == mq.getDoTime()){
						mq.setDoTime("暂无数据");
					}else{
						if(Integer.valueOf(mq.getDoTime()) <= 1){
							mq.setDoTime("5");
						}
					}
					if(null == mq.getNum()){
						mq.setNum("暂无数据");
					}
					if(null ==mq.getWaitTime()){
						mq.setWaitTime("暂无数据");
					}
					MobileAreaType ma = mobileQueueService.findUserByNumberOther(orgrizeId);
					mq.setAddress(ma.getOrgrizeAddress());
					mq.setAreaAddr(ma.getAbbreviationName());
					custom.put("data",mq);
				}
			}
			custom.put("text","获取成功！");
			custom.put("code",200);
		}catch (Exception e){
			custom.put("text","获取失败！");
			custom.put("code",400);
		}
		status.put("code",200);
		status.put("text","");
		result.put("custom",custom);
		result.put("status",status);
		return  result;
	}

	/**
	 * 发送注册验证码
	 * tell手机号
	 */
	@PostMapping("sendSmsGX")
	@CrossOrigin
	public Object sendSmsGX(HttpServletRequest req) {
		String ipAddr = req.getRemoteAddr();
		String str, body = "";
		Map<String,Object> result = new HashedMap();
		Map<String,Object> custom = new HashedMap();
		Map<String,Object> status = new HashedMap();
		String verificationCode = String.valueOf(RandomUtil.nextInt(100000, 999999));
		try {
			//发送短信
			BufferedReader reader = req.getReader();
			while((str = reader.readLine()) != null){
				body += str;
			}
			reader.close();
			if("" != body){
				body = URLDecoder.decode(body, "UTF-8");
				JSONObject jsonObject = JSONObject.fromObject(body);
                byte[] decodedBytes = Base64.getDecoder().decode(jsonObject.getJSONObject("params").getString("tell"));
                String tell =new String(decodedBytes);
				send.sendSmsVerificationCode(tell,verificationCode);
				CacheUtils.put(MobileLoginController.VERIFICATION_CODE_CACHE, tell, verificationCode);
				custom.put("text","获取成功！");
				custom.put("code",200);
			}
		} catch (Exception e) {
            e.printStackTrace();
			custom.put("text","获取失败！");
			custom.put("code",400);
		}
		status.put("code",200);
		status.put("text","");
		result.put("custom",custom);
		result.put("status",status);
		return  result;
	}

	/**
	 * 生成二维码
	 *
	 * @throws Exception
	 */
	/**
	 * 生成二维码
	 *
	 * @throws Exception
	 */
	@PostMapping("createGXTellCode")
	@CrossOrigin
	public Object createGXTellCode(HttpServletRequest req) {
		String ipAddr = req.getRemoteAddr();
		String str, body = "";
		Map<String,Object> result = new HashedMap();
		Map<String,Object> custom = new HashedMap();
		Map<String,Object> status = new HashedMap();
		try {
			//发送短信
			BufferedReader reader = req.getReader();
			while((str = reader.readLine()) != null){
				body += str;
			}
			reader.close();
			if("" != body){
				body = URLDecoder.decode(body, "UTF-8");
				JSONObject jsonObject = JSONObject.fromObject(body);
                // 使用Base64解码
                byte[] decodedBytestell = Base64.getDecoder().decode(jsonObject.getJSONObject("params").getString("tell"));
                // 将字节数组转换为字符串
				String tell = new String(decodedBytestell);
                System.out.println(tell);
                byte[] decodedBytestellCode = Base64.getDecoder().decode(jsonObject.getJSONObject("params").getString("tellCode"));
				String tellCode = new String(decodedBytestellCode);
                System.out.println(tellCode);
                byte[] decodedBytesorgrizeId = Base64.getDecoder().decode(jsonObject.getJSONObject("params").getString("orgrizeId"));
				String orgrizeId = new String(decodedBytesorgrizeId);
                System.out.println(orgrizeId);
				Object cacheInfo = CacheUtils.get(MobileLoginController.VERIFICATION_CODE_CACHE, tell);
				if (null == cacheInfo) {
					custom.put("text","验证码无效！");
					custom.put("code",400);
				}else {
					CacheUtils.remove(MobileLoginController.VERIFICATION_CODE_CACHE, tell);
					if (cacheInfo.toString().equalsIgnoreCase(tellCode)) {
						int resultList = mobileLoginService.findUserValue(tell);
						if(resultList >= 1 && mobileLoginService.findUserValueNum() >= 20){
							custom.put("text","名额已满！");
							custom.put("code",400);
						}else{
							String uuid = "gxls"+UUID.randomUUID().toString();
							userService.insertQR(uuid,DateUtils.getDateTime(),600,"oyyT9s8WTu-wfSt3ZX2QSnC6FbbU",tell);
							MobileAreaType ma = mobileQueueService.findUserByNumberOther(orgrizeId);
							Map<String,Object> mq = new HashedMap();
							mq.put("address",ma.getOrgrizeAddress());
							mq.put("areaAddr",ma.getAbbreviationName());
							mq.put("url",qrUrl + uuid);
							custom.put("text","获取成功！");
							custom.put("code",200);
							custom.put("data",mq);
						}
					}else{
						custom.put("text","验证码无效！");
						custom.put("code",400);
					}
				}
			}
		}catch (Exception e) {
			custom.put("text","获取失败！");
			custom.put("code",400);
		}
		status.put("code",200);
		status.put("text","");
		result.put("custom",custom);
		result.put("status",status);
		return  result;
	}

	/**
	 * listGXAreaTypeValue 获取点位标识区分集合
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@PostMapping("/listGXAreaTypeValue")
	@CrossOrigin
	public Object listGXAreaTypeValue(HttpServletRequest req) {
		String ipAddr = req.getRemoteAddr();
		String str, body = "";
		Map<String,Object> result = new HashedMap();
		Map<String,Object> custom = new HashedMap();
		Map<String,Object> status = new HashedMap();
		try{
			BufferedReader reader = req.getReader();
			while((str = reader.readLine()) != null){
				body += str;
			}
			reader.close();
			if("" != body){
				body = URLDecoder.decode(body, "UTF-8");
				JSONObject jsonObject = JSONObject.fromObject(body.trim());
				String orgrizeId = jsonObject.getJSONObject("params").getString("orgrizeId");
				String number = jsonObject.getJSONObject("params").getString("number");
				if(StringUtils.isNotBlank(orgrizeId) && StringUtils.isNotBlank(number)){
					number = number.toUpperCase();
					MobileQueueValue mq = mobileQueueService.getQueueValue(number, orgrizeId,number.substring(0,number.length()-3));
					if(null == mq){
						mq = new MobileQueueValue();
					}
					if(null == mq.getDoTime()){
						mq.setDoTime("暂无数据");
					}else{
						if(Integer.valueOf(mq.getDoTime()) <= 1){
							mq.setDoTime("5");
						}
					}
					if(null == mq.getNum()){
						mq.setNum("暂无数据");
					}
					if(null ==mq.getWaitTime()){
						mq.setWaitTime("暂无数据");
					}
					MobileAreaType ma = mobileQueueService.findUserByNumberOther(orgrizeId);
					mq.setAddress(ma.getOrgrizeAddress());
					mq.setAreaAddr(ma.getAbbreviationName());
					custom.put("data",mq);
				}
			}
			custom.put("text","获取成功！");
			custom.put("code",200);
		}catch (Exception e){
			custom.put("text","获取失败！");
			custom.put("code",400);
		}
		status.put("code",200);
		status.put("text","");
		result.put("custom",custom);
		result.put("status",status);
		return  result;
	}

	/**
	 * findAreaNameValue 获取点位办理 地址
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "findAreaNameValue")
	public AjaxJson findAreaNameValue(String areaId) {
		return AjaxJson.success("get data success!").put("data", mobileSilentService.findAreaNameValue(areaId));
	}

	/**
	 * checkOtherUser 核对第三方是否实名认证
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping(value = "checkOtherUser")
	public AjaxJson checkOtherUser(String openid) {
		if (null == userService.getUserIdcard(openid)) {
			return AjaxJson.error("未实名");
		}else{
			return AjaxJson.success("已实名!");
		}
	}

	/**
	 * recordsByWXId 通过微信id获取预约信息
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/recordsByWXId")
	public Result<List<AppointmentRecordOut>> recordsByWXId(String openid) {
		return Result.succeed(appointmentService.recordsByWXId(openid), "");
	}

	@GetMapping("/cancelOtherYY")
	public Result<Boolean> cancelOtherYY(String id) {
		CancelAppointment ca = new CancelAppointment();
		ca.setId(id);
		return Result.succeed(appointmentService.cancel(ca), "");
	}

	/**
	 * 获取用户二维码信息-对接税务
	 *
	 * @throws Exception
	 */
	@GetMapping("getUserValue")
	public AjaxJson getUserValue(String id) {
		try {
			if(StringUtils.isNotBlank(id)){
				MobileUserQR mobileUserQR = userService.getUserIdcard(id);
				MobileLegal legalValue = userService.getLegalValue(id);
				if(null != legalValue && null != legalValue.getIdcard()){
					return AjaxJson.success("加载成功！").put("isLegal",true).put("data", EncryptUtils.aesEncrypt(JSONObject.fromObject(mobileUserQR).toString(), GX_PUBLIC_KEY)).put("legalValue",EncryptUtils.aesEncrypt(JSONObject.fromObject(legalValue).toString(), GX_PUBLIC_KEY));
				}else{
					return AjaxJson.success("加载成功！").put("isLegal",false).put("data", EncryptUtils.aesEncrypt(JSONObject.fromObject(mobileUserQR).toString(), GX_PUBLIC_KEY));
				}
			}else{
				log.error("参数无效！id:"+id);
				return AjaxJson.error("参数无效！");
			}
		} catch (Exception e) {
			log.error("二维码生成失败:"+e.getMessage());
			return AjaxJson.error("二维码生成失败");
		}
	}

	@GetMapping("/getCloseValue")
	public AjaxJson getCloseValue() {
		return AjaxJson.success().put("data",mobileQueueService.getCloseValue());
	}

	@GetMapping("/getCloseISDo")
	public AjaxJson getCloseValue(String oid) {
		List<Map<String,String>> map = mobileQueueService.getCloseValue();
		if(!map.isEmpty()){
			List<String> list = new ArrayList<String>();
			for(Map<String,String> m : map){
				if(null != m.get("areaId"))
					list.add(m.get("areaId"));

			}
			if(mobileMatterService.findAreaIdByOid(oid,list).isEmpty()){
				return AjaxJson.success().put("isGo",false);
			}
		}
		return AjaxJson.success().put("isGo",true);

	}
	/**
	 * 对接一码办成事获取用户信息二维码链接
	 *
	 */
	@RequestMapping(value = "/ymbcsButtJoint", method = RequestMethod.GET)
	public AjaxJson ymbcsButtJoint(String uuid,HttpServletRequest request) {
        String  publicIp = UserUtils.getClientIpAddress(request);
        if(userService.checkUserIp(publicIp) <= 0){
            return AjaxJson.error("非法ip:"+publicIp);
        }
			if(StringUtils.isNotBlank(uuid) && uuid.lastIndexOf("/") >= 0){
				uuid = uuid.substring(uuid.lastIndexOf("/")+1,uuid.length());
			}
			MobileGxUser mu = userService.getGxUserCode(uuid);
			if(null == mu){
				return AjaxJson.error("暂无此数据！");
			}else{
				mu.setBirthday(mu.getIdcard().substring(6,10));
				int sex = Integer.parseInt(mu.getIdcard().substring(16,17));
				if (sex % 2 == 0) {
					mu.setSex("女");
				} else {
					mu.setSex("男");
				}
				mobileIndexService.intoUserZZJ(mu.getName(),mu.getIdcard(),mu.getTell());
				mu.setList(userService.findUserMaterial(mu.getIdcard()));
				return AjaxJson.success().put("data",mu);
			}
	}
    /**
     * 对接一码办成事获取用户信息二维码链接
     *
     */
    @RequestMapping(value = "/ymbcsImgsImages", method = RequestMethod.POST)
    public AjaxJson ymbcsImgsImages(String id,HttpServletRequest request) {
        String  publicIp = UserUtils.getClientIpAddress(request);
        if(userService.checkUserIp(publicIp) <= 0){
            return AjaxJson.error("非法ip:"+publicIp);
        }
        String url = electronicMaterialService.getURLById(id);
        if (!"".equals(url) && null != url) {
            url = url.replace("/api", "");
            String fileDir = FileKit.getFileUrl(url);
            return AjaxJson.success().put("data",getImgBase64Str(fileDir));
        }
        return null;
    }
    public  String getImgBase64Str(String imgFile) {
        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return org.apache.commons.codec.binary.Base64.encodeBase64String(data);
    }

	@PostMapping(value ="todayManager")
	public AjaxJson todayManager() {
		return mobileQueueService.todayManager();
	}

	@RequestMapping(value = "/getXJHSBQueue", method = RequestMethod.GET)
	public String getXJHSBQueue(String time) {
		if(StringUtils.isBlank(time))time = DateUtils.getDate();
		return time+":"+String.valueOf(mobileXJHQueueService.getXJHSBQueue(time))+"件";
	}
	/**
	 * 芳草排叫号数据
	 * fcjjdQueueInfo
	 */
	@GetMapping(value ="fcjjdQueueInfo")
	public AjaxJson fcjjdQueueInfo(String startTime,String endTime){
		return AjaxJson.success().put("data",mobileQueueService.fcjjdQueueInfo(startTime, endTime));
	}
	/**
	 * 成都市政务排号对接-可预约时间段查询接口
	 *
	 */
	@PostMapping(value ="cdszwphsj")
	public Map<String,Object> cdszwphsj(HttpServletRequest request,@RequestBody String requestBody){
        JSONObject jsonObject = JSONObject.fromObject(requestBody);
        JSONObject data = jsonObject.getJSONObject("data");
		Map<String,Object> mapReturn=new HashMap<>();
		mapReturn.put("appid",jsonObject.getString("appid"));
		mapReturn.put("aaz001",jsonObject.getString("aaz001"));
		mapReturn.put("aaz002",UUID.randomUUID());

		String  publicIp = UserUtils.getClientIpAddress(request);
		if(userService.checkUserIp(publicIp) <= 0){
			mapReturn.put("status","0");
			mapReturn.put("message","非法ip:"+publicIp);
			return mapReturn;
		}
		List<Map<String,String>> list =new ArrayList<>();
		mapReturn.put("status","1");
		mapReturn.put("message","200-请求成功");
		String orgrizeId = mobileQueueService.getOrgrizeId(data.getString("itemCode"));
		List<ServiceTime> serviceTime = appointmentService.getServiceTime(orgrizeId, data.getString("itemCode"));
		for (int i = 0; i < serviceTime.size(); i++) {
			String time = serviceTime.get(i).getTime();
			SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMdd");
			String formattedDate ="";
			try {
				Date date = inputFormat.parse(time);
				formattedDate = outputFormat.format(date);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (formattedDate.equals(data.getString("dayTime"))) {

				List<ServiceTime.Detail> details = serviceTime.get(i).getDetails();
				for (int k = 0; k < details.size(); k++) {
					Map<String, String> map = new HashMap<>();
					ServiceTime.Detail detail = details.get(k);
					String timePeriodStr = detail.getTimePeriodStr();
					String[] split1 = timePeriodStr.split("-");
					map.put("timeStart", split1[0]);
					map.put("timeEnd", split1[1]);
					map.put("allowNum", detail.getQuota() + "");
					list.add(map);
				}
			}
			mapReturn.put("list", list);
		}
			return mapReturn;
	}
	/**
	 * 成都市政务排号对接-政务预约排号接口
	 *
	 */
	@PostMapping(value ="cdszwphsc")
	public Map<String,Object> cdszwphsc(HttpServletRequest request,@RequestBody String requestBody){
        JSONObject jsonObject = JSONObject.fromObject(requestBody);
        JSONObject data = jsonObject.getJSONObject("data");
		Map<String,Object> mapReturn=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
		mapReturn.put("appid",jsonObject.getString("appid"));
		mapReturn.put("aaz001",jsonObject.getString("aaz001"));
		mapReturn.put("aaz002",UUID.randomUUID());

		String  publicIp = UserUtils.getClientIpAddress(request);
		if(userService.checkUserIp(publicIp) <= 0){
			mapReturn.put("status","0");
			mapReturn.put("message","非法ip:"+publicIp);
            mapReturn.put("data",map);
			return mapReturn;
		}
		if (StringUtils.isBlank(data.getString("aac002")) || StringUtils.isBlank(data.getString("aac003")) || StringUtils.isBlank(data.getString("phone")) || StringUtils.isBlank(data.getString("itemCode"))|| StringUtils.isBlank(data.getString("dayTime"))|| StringUtils.isBlank(data.getString("timeStart"))) {
			mapReturn.put("status","0");
			mapReturn.put("message","400-参数不合法！");
            mapReturn.put("data",map);
			return mapReturn;
		}
		String orgrizeId = mobileQueueService.getOrgrizeId(data.getString("itemCode"));
		ModAppointment mt = new ModAppointment();
		mt.setBusinessId(data.getString("itemCode"));
		mt.setSysNo(orgrizeId);
		SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
		String formattedDate ="";

		try {
			Date date = inputFormat.parse(data.getString("dayTime"));
			 formattedDate = outputFormat.format(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		mt.setTime(formattedDate);
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
		LocalTime time = LocalTime.parse(data.getString("timeStart"));
		int hour = time.getHour();
		mt.setTimePeriod(hour);
		mt.setSysName("成都市政务排号");
		mt.setMatterId("");
		Result<ModAppointmentOut> result = appointmentService.saveAppointment(mt, true, data.getString("aac002"), data.getString("phone"), data.getString("aac003"));
		if (result.getResp_code() == HttpStatus.OK.value()) {
			mapReturn.put("status","1");
			mapReturn.put("message","200-请求成功");
			return mapReturn;
		} else {
			mapReturn.put("status","0");
			mapReturn.put("message",result.getResp_msg());
			return mapReturn;
		}
    }
	/**
	 * 成都市政务排号对接-预约排号历史查询接口
	 *
	 */
	@PostMapping(value ="cdszwphls")
	public Map<String,Object> cdszwphls(HttpServletRequest request,@RequestBody String requestBody) {
        JSONObject jsonObject = JSONObject.fromObject(requestBody);
        JSONObject data = jsonObject.getJSONObject("data");
		Map<String,Object>mapReturn=new HashMap<>();
		mapReturn.put("appid",jsonObject.getString("appid"));
		mapReturn.put("aaz001",jsonObject.getString("aaz001"));
		String  publicIp = UserUtils.getClientIpAddress(request);
		if(userService.checkUserIp(publicIp) <= 0){
			mapReturn.put("status","0");
			mapReturn.put("message","非法ip:"+publicIp);
			return mapReturn;
		}
		mapReturn.put("status","1");
		mapReturn.put("message","200-请求成功");
		String isTakeNum="";
        String isHandle="";
        if(data.has("isTakeNum")){
            isTakeNum=data.getString("isTakeNum");
        }
        if(data.has("isHandle")){
            isHandle=data.getString("isHandle");
        }
		List<Map<String, String>> ybjAppointmentInfoHistory = rongYiBanService.getYBJAppointmentInfoHistory(data.getString("aac002"), isTakeNum, isHandle,data.getString("pageIndex") ,data.getString("pageSize") );

		for (int i = 0; i < ybjAppointmentInfoHistory.size(); i++) {
			Map<String, String> map = mobileQueueService.cdszwphgetSpotBySpotCode(ybjAppointmentInfoHistory.get(i).get("spotCode"));
            Map<String, String> stringMap = mobileQueueService.cdszwphgetClassificationByitemCodeItemCode(ybjAppointmentInfoHistory.get(i).get("itemCode"));
            if("二级点位".equals(map.get("spotType"))){
				ybjAppointmentInfoHistory.get(i).put("spotType","区级政务中心");
				ybjAppointmentInfoHistory.get(i).put("spotCode","510109000000");
				ybjAppointmentInfoHistory.get(i).put("spotName","成都高新区政务服务中心");
				ybjAppointmentInfoHistory.get(i).put("spotAddress","成都市益州大道中段999号");
				if(null!=stringMap && !stringMap.isEmpty()){
                    ybjAppointmentInfoHistory.get(i).put("departmentCode",stringMap.get("departmentCode"));
                    ybjAppointmentInfoHistory.get(i).put("departmentName",stringMap.get("departmentName"));
                }else{
                    ybjAppointmentInfoHistory.get(i).put("departmentCode","510109000000");
                    ybjAppointmentInfoHistory.get(i).put("departmentName","全部业务");
                }

			}else {
				ybjAppointmentInfoHistory.get(i).putAll(map);
                ybjAppointmentInfoHistory.get(i).put("departmentCode",ybjAppointmentInfoHistory.get(i).get("spotCode"));
                ybjAppointmentInfoHistory.get(i).put("departmentName","全部业务");
			}

		}
		mapReturn.put("list",ybjAppointmentInfoHistory);
		return mapReturn;
	}
	/**
	 * 成都市政务排号对接-服务网点查询接口
	 *
	 */
	@PostMapping(value ="cdszwphgetSpot")
	public Map<String,Object> cdszwphgetSpot(HttpServletRequest request,@RequestBody String requestBody){
		JSONObject jsonObject = JSONObject.fromObject(requestBody);
		JSONObject data = jsonObject.getJSONObject("data");
		Map<String,Object> mapReturn=new HashMap<>();
		mapReturn.put("appid",jsonObject.getString("appid"));
		mapReturn.put("aaz001",jsonObject.getString("aaz001"));
		mapReturn.put("aaz002",UUID.randomUUID());
		String  publicIp = UserUtils.getClientIpAddress(request);
		if(userService.checkUserIp(publicIp) <= 0){
			mapReturn.put("status","0");
			mapReturn.put("message","非法ip:"+publicIp);
			return mapReturn;
		}
		mapReturn.put("status","1");
		mapReturn.put("message","200-请求成功");
		List<Map<String, Object>> list = mobileQueueService.cdszwphgetSpot();
		mapReturn.put("list",list);
		return mapReturn;
	}
	/**
	 * 成都市政务排号对接-业务事项查询接口
	 *
	 */
	@PostMapping(value ="cdszwphyw")
	public Map<String,Object> cdszwphyw(HttpServletRequest request,@RequestBody String requestBody){
		JSONObject jsonObject = JSONObject.fromObject(requestBody);
		JSONObject data = jsonObject.getJSONObject("data");
		Map<String,Object> mapReturn=new HashMap<>();
		mapReturn.put("appid",jsonObject.getString("appid"));
		mapReturn.put("aaz001",jsonObject.getString("aaz001"));
		mapReturn.put("aaz002",UUID.randomUUID());
		String  publicIp = UserUtils.getClientIpAddress(request);
		if(userService.checkUserIp(publicIp) <= 0){
			mapReturn.put("status","0");
			mapReturn.put("message","非法ip:"+publicIp);
			return mapReturn;
		}
		mapReturn.put("status","1");
		mapReturn.put("message","200-请求成功");
			if("510109000000".equals(data.getString("spotCode"))){
				List<Map<String, Object>> cdszwphgetClassification = mobileQueueService.cdszwphgetClassification(data.getString("spotCode"));
				for (int i = 0; i < cdszwphgetClassification.size(); i++) {
					List<Map<String, Object>> list = mobileQueueService.cdszwphgetBusinessByDepartmentName(cdszwphgetClassification.get(i).get("departmentName").toString());
					cdszwphgetClassification.get(i).put("children",list);
				}
				mapReturn.put("list",cdszwphgetClassification);
				return mapReturn;
			}else{
				List<Map<String, Object>> listmap=new ArrayList<>();
				Map<String,Object> map=new HashMap<>();
				List<Map<String, Object>> list = mobileQueueService.cdszwphgetBusiness(data.getString("spotCode"));
				map.put("departmentCode",data.getString("spotCode"));
				map.put("departmentName","全部业务");
				map.put("children",list);
				listmap.add(map);
				mapReturn.put("list",listmap);
				return mapReturn;
			}
	}

	/**
	 * 成都市政务排号对接-可预约排号日期查询接口
	 *
	 */
	@PostMapping(value ="cdszwphrq")
	public Map<String,Object> cdszwphrq(HttpServletRequest request,@RequestBody String requestBody){
		JSONObject jsonObject = JSONObject.fromObject(requestBody);
		JSONObject data = jsonObject.getJSONObject("data");
		Map<String,Object> mapReturn=new HashMap<>();
		mapReturn.put("appid",jsonObject.getString("appid"));
		mapReturn.put("aaz001",jsonObject.getString("aaz001"));
		mapReturn.put("aaz002",UUID.randomUUID());

		String  publicIp = UserUtils.getClientIpAddress(request);
		if(userService.checkUserIp(publicIp) <= 0){
			mapReturn.put("status","0");
			mapReturn.put("message","非法ip:"+publicIp);
			return mapReturn;
		}
		mapReturn.put("status","1");
		mapReturn.put("message","200-请求成功");
		List<Map<String,Object>>list=new ArrayList<>();
		String orgrizeId = mobileQueueService.getOrgrizeId(data.getString("itemCode"));
		List<ServiceTime> serviceTime = appointmentService.getServiceTime(orgrizeId, data.getString("itemCode"));
		for (int i = 0; i < serviceTime.size(); i++) {
			String time = serviceTime.get(i).getTime();
			SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat outputFormat = new SimpleDateFormat("yyyyMMdd");
			try {
				Map<String,Object> map=new HashMap<>();
				Date date = inputFormat.parse(time);
				map.put("dayTime",outputFormat.format(date));
				map.put("allowNum",serviceTime.get(i).getQuota());
				list.add(map);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		mapReturn.put("dayTimeList",list);
		return mapReturn;
	}
	/**
	 * getBussNumberById 获取点位信息
	 *
	 * @author azj
	 * @version 2020-04-24
	 */
	@GetMapping("/getQueueValues")
	public AjaxJson getQueueValues(String number) {
		return AjaxJson.success().put("data",mobileSilentService.getQueueValue(number,"5101090000004"));
	}

	/**
	 * 获取用户信息解密密钥
	 * loseTime二维码链接失效时间
	 */
	@RequestMapping(value = "/checkKeys", method = RequestMethod.GET)
	public AjaxJson checkKeys() {
		return AjaxJson.success().put("data","加载成功");
	}


}
